package com.qf.commons.web.exception;

import com.qf.commons.data.result.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * author Ken
 * create_time 2022/8/17
 */
@RestControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice {

    /**
     * supports 方法如果返回true  beforeBodyWrite方法才会执行
     * @param returnType the return type
     * @param converterType the selected converter type
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getMethod().getReturnType() == R.class;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        R result = (R) body;
        if (result.getCode() != 200) {
            //如果响应的结果未成功，则修改响应的响应码
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return result;
    }
}
